import cv2
import mediapipe
import time

cap = cv2.VideoCapture(0)
time1 = 0

#加载api
handdetect = mediapipe.solutions.hands.Hands()
draw = mediapipe.solutions.drawing_utils
mp_drawing_styles = mediapipe.solutions.drawing_styles


while True:
    success,img = cap.read()

    RGB_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

    #检测手部，打印位置信息
    returns = handdetect.process(RGB_img)

    X_list = []
    Y_list = []

    if(returns.multi_hand_landmarks):
        for landmarks in returns.multi_hand_landmarks:
            #print(landmarks)
            draw.draw_landmarks(img,landmarks,mediapipe.solutions.hands.HAND_CONNECTIONS)
                               # mp_drawing_styles.get_default_hand_landmarks_style(),
                               # mp_drawing_styles.get_default_hand_connections_style())

            for id, landmark in enumerate(landmarks.landmark):
                #print(id,landmark)
                H,W,_ = img.shape
                x,y = int(landmark.x * W) , int(landmark.y * H)
                X_list.append(x)
                Y_list.append(y)

                print(id,x,y)

            x_min,y_min = min(X_list) , min(Y_list)
            x_max,y_max = max(X_list) , max(Y_list)

            cv2.rectangle(img,(x_min-20,y_min-20),(x_max + 20 , y_max + 20), (0,200,100),2)


    #设置FPS
    time2 = time.time()
    fps = 1/(time2-time1)
    time1 = time2
    cv2.putText(img,f'FPS : {int(fps)}',(30,30),cv2.FONT_HERSHEY_PLAIN,2,(0,255,0),2)

    cv2.imshow("output",img)
    if cv2.waitKey(1) & 0xff == 27:
        break

cap.release()
